$(function(argument) {
	// alert(WXobj);
	// console.log(WXobj);

	if (GetQueryString('openid') != null) {
		$('#wx').attr('checked', 'checked');
	}
	$('#wx').click(function() {
			window.location.href = 'http://www.teaweilai.com/app/Admin/PaymentWx/getOpenid.html';
		})
		//获取oppid
	function GetQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	}


	$(".glyphicon-menu-left").click(function(event) {
		window.sessionStorage.removeItem(fromDetail);
		window.history.back();
		
	});
	var uid = window.localStorage.getItem("user_id");
	var pay_id;
	var pay_name;
	var consignee;
	var phoneNumber;
	var userAdress;
	var changeAddress;
	var goodsAllSub;

	var fromDetail = window.sessionStorage.getItem("fromDetail");
	// var fromCar = window.sessionStorage.getItem("fromCar");
	// 获取总积分接口
	function getPoint(uid) {
		$.ajax({
			url: 'http://www.teaweilai.com/app/Admin/Order/CountPoint',
			type: 'POST',
			dataType: 'json',
			data: {
				uid: uid
			},
			success: function(data) {
				// console.log(data)
				if (data.code == 200) {
					if (data.sing.pay_points != 0) {
						$(".prize").html("共" + data.sing.pay_points + "积分，抵用<span class='surePrize'>" + (Number(data.sing.pay_points) / 100).toFixed(2) + "</span>元")
					}
					if (data.sing.pay_points == 0) {
						$(".prize").html("您还没有可抵现积分")
						$(".ui-switch").css({
							display: 'none'
						});
					}
				}
			}
		})

	}

	// 获取现金券
	getPrize(uid);

	function getPrize(uid) {
		$.ajax({
				url: 'http://www.teaweilai.com/app/Admin/AppRandom/RanDetail',
				type: 'POST',
				dataType: 'json',
				data: {
					uid: uid
				}
			})
			.done(function(data) {
				// console.log(data);
				if (data.code == 200) {
					var strO = "";
					for (var i = 0; i < data.sing.length; i++) {
						//
						strO += "<option data-random_id=" + data.sing[i].random_id + " data-random_money=" + data.sing[i].random_money + ">" + data.sing[i].random_money + "元抵用券</option>"
					}
					$(".getPrize").html("<option data-random_money='0'>请选择抵用券</option>" + strO);
				} else if (data.code == 500) {
					$(".getPrize").html("<option data-random_money='0'>您还没有抵用券</option>");
				}
				actual_payment()
			})
			.fail(function() {
				console.log("error");
			})
	}
	// 差多少钱送券
	function getCouponErrand() {
		goodsAllSub = $(".goods");
		var allGoods = [];
		for (var i = 0; i < goodsAllSub.length; i++) {
			var oneGoods = {};
			oneGoods.goods_number = $(goodsAllSub).eq(i).find(".number").eq(0).html();
			oneGoods.goods_price = $(goodsAllSub).eq(i).find(".teaPrice").eq(0).html();
			oneGoods.seller_id = $(goodsAllSub).eq(i).parents(".shop").find(".shops").attr('data-seller_id');
			allGoods.push(oneGoods);
		}
		$.ajax({
				url: 'http://www.teaweilai.com/app/admin/Order/SongQuan',
				type: 'POST',
				dataType: 'json',
				data: {
					arr: allGoods
				}
			})
			.done(function(data) {
				console.log(data);
				if (data.code == 500) {
					return $(".sendCoupon").hide();
				}
				if (data.code == 200) {
					return $(".sendCoupon").html("您即将获得面值" + data.sing + "的茶券");

				}
			})
			.fail(function() {
				console.log("error");
			})
	}

	if (fromDetail == 1) {
		// 从详情也直接支付
		var gid = window.sessionStorage.getItem("gid");
		var number = window.sessionStorage.getItem("number");
		$.ajax({
				url: 'http://www.teaweilai.com/app/Admin/AppGoodsInfo/goodsInfo',
				type: 'POST',
				dataType: 'json',
				data: {
					gid: gid
				},
			})
			.done(function(data) {
				// console.log(data);
				var strOneShop = '<div class="border shop">' +
					'<div class = "border shopTitle">' +
					'<div class = "selectCon">' +
					'</div> ' +
					'<a href="#" class="shops" data-seller_id=' + data.sing.seller_id + '>' + data.sing.seller_name + '</a>' +
					'</div>' +
					'<div class = "goodsList">' +
					'<a href = "#" class = "goods clearfix" data-goods_id=' + data.sing.goods_id + ' data-is_coupon=' + data.sing.is_coupon + '>' +
					'<div class = "media">' +
					'<div class = "media-left">' +
					'<img class = "media-object" src =' + data.sing.goods_img + '>' +
					'</div>' +
					'<div class = "media-body">' +
					'<h4 class = "media-heading">' + data.sing.goods_name + '</h4> ' +
					'<span class = "teaWeight">' + data.sing.goods_heft + 'g</span><span class = "teaPrice">' + data.sing.shop_price + '</span>x<span class="number">' + number + '</span>' +
					'<span class = "onePay">  </span>元' +
					'</div> ' +
					'</div> ' +
					'</a> ' +
					'</div>' +
					'</div>';

				$(".goodsAll").html(strOneShop);
				getAll();
				actual_payment();
				getCouponErrand()
			})
			.fail(function() {
				console.log("error");
			})

		// 获取茶券
		$.ajax({
			url: 'http://www.teaweilai.com/app/Admin/Order/TeaQuan',
			type: 'POST',
			dataType: 'json',
			data: {
				'uid': uid,
				'goods_id': gid
			},
			success: function(data) {
				// console.log(data);
				if (data.code == 200) {
					$('.shop').find('.goods').attr('data-is_coupon', 1)
					if ($(".yinchaquan").text() == "") {
						var ht = ''
						for (var i = 0; i < data.sing.length; i++) {
							ht += '<label for=""><input class="yin_quanL" type="checkbox" data_no="' + data.sing[i].coupon_no + '" data_money="' + data.sing[i].money + '" value="' + data.sing[i].coupon_id + '"> ' + '<p>茶券号' + data.sing[i].coupon_no + '</p>' + '<p>面值' + data.sing[i].money + '元</p></label>';
						}
						ht += '<input type="button" class="btn select_quan" value="确定">'
						$(".yinchaquan").html(ht);
					}
				}
			}
		})
		getPoint(uid);
		getAll();
		actual_payment();
		window.sessionStorage.removeItem(fromDetail);
	} else {
		// 从购物车过来的
		consignee = window.sessionStorage.getItem("consignee");
		phoneNumber = window.sessionStorage.getItem("phoneNumber");
		userAdress = window.sessionStorage.getItem("userAdress");
		changeAddress = window.sessionStorage.getItem("changeAddress");
		// 删除没有商品的商家
		function _shopname() {
			var a = $('.goodsList');
			for (var i = 0; i < a.length; i++) {
				if ($(a).eq(i).find('.goods').length == 0) {
					// 没有商品信息
					$(a).eq(i).parents('.shop').remove();
				}
			}
		}
		// 获取茶券  4.26改
		function get_gid(gid, seller_id, tag) {
			$.ajax({
				url: 'http://www.teaweilai.com/app/Admin/Order/TeaQuan',
				type: 'POST',
				dataType: 'json',
				data: {
					'uid': uid,
					'seller_id': seller_id,
					'goods_id': gid
				},
				// 获取茶券
				success: function(data) {
					console.log(data);
					if (data.code == 200) {
						$(tag).parents('.shop').find('.goods').attr('data-is_coupon', 1)
						if ($(".yinchaquan").text() == "") {
							var ht = ''
							for (var i = 0; i < data.sing.length; i++) {
								ht += '<label for=""><input class="yin_quanL" type="checkbox" data_no="' + data.sing[i].coupon_no + '" data_money="' + data.sing[i].money + '" value="' + data.sing[i].coupon_id + '"> ' + '<p>茶券号' + data.sing[i].coupon_no + '</p>' + '<p>面值' + data.sing[i].money + '元</p></label>';
							}
							ht += '<input type="button" class="btn select_quan" value="确定">'
							$(".yinchaquan").html(ht);
						}
					}
				}
			})
		}

		//获取购物车选中的商品
		$.ajax({
			url: 'http://www.teaweilai.com/app/Admin/AppCart/cartList',
			type: 'POST',
			dataType: 'json',
			data: {
				uid: uid
			},
			success: function(data) {
				console.log(data);
				var strOrderList = template("orderOne", {
					order: data
				});
				$(".goodsAll").html(strOrderList);
				_shopname();
				var goods = $(".goods");
				for (var i = 0; i < goods.length; i++) {
					var gid = $(goods).eq(i).attr('data-goods_id');
					var seller_id = $(goods).eq(i).parents('.shop').find('.shops').attr('data-seller_id');
					// console.log(gid);
					get_gid(gid, seller_id, $(goods).eq(i));
				}
				getPoint(uid);
				getAll();
				actual_payment();
				getCouponErrand()
			}

		})
	}


	// 计算商品总价格
	function getAll() {
		var allPay = 0;
		$(".onePay").each(function(i, e) { //每一个商品的价格
			$(this).html(Number($(this).siblings('.teaPrice').text()) * Number($(this).siblings('.number').text()));
		})
		$(".onePay").each(function(index, el) {
			allPay += Number($(this).text());
		});
		$(".allPay").html(allPay);
	}
	// 实际支付
	function actual_payment() {
		var actual_payment = 0;
		$(".onePay").each(function(index, el) {
			actual_payment += Number($(this).text());
		});
		// 积分抵现判段
		// console.log(actual_payment)
		if ($(".ui-switch input:checked").attr('checked') == "checked") {
			if (Number($(".surePrize").html())) { //积分不为0时
				if ((Number(actual_payment) - Number($(".surePrize").html())) <= 0) {
					actual_payment = 0;
				} else {
					actual_payment = Number(actual_payment) - Number($(".surePrize").html());
				}
			}
		}
		var changeNum = Number($(".getPrize option:checked").attr('data-random_money'));
		if (changeNum <= actual_payment) {
			actual_payment -= changeNum;
		} else {
			actual_payment = 0;
		}
		$(".actual_payment").html(actual_payment.toFixed(2));
	}
	// 点击选择积分抵用券
	$(".getPrize").change(function() {
		actual_payment();
	})

	// 选择使用积分
	$(".ui-switch input").click(function() {
		actual_payment();
	})

	// 点击优惠券，改变面额
	$(document).on("change", ".selectCons", function(event) {
		var counponMoney = Number($(".selectCons option:checked").attr('data-money'));
		var goodsMoney = Number($(".selectCons").parents(".shop").find(".teaPrice").eq(0).html()) * Number($(".selectCons").parents(".shop").find(".number").eq(0).html());
		if (counponMoney >= goodsMoney) {
			$(".selectCons").parents(".shop").find(".onePay").eq(0).html(0);
		} else {
			var difference = goodsMoney - counponMoney;
			$(".selectCons").parents(".shop").find(".onePay").eq(0).html(difference);
		}
		actual_payment();
	});



	// 点击提交
	// 提交给后台的数据
	var allGoods = []; //所有商品
	$(".btnSuccess").click(function() {
			var zongjiage = $(".actual_payment").html();
			goodsAllSub = $(".goods");
			// pay_id
			if ($(".howPay input:checked").next("span").eq(0).html() == "支付宝") {
				pay_id = 1;
				pay_name = "支付宝";
			} else {
				pay_id = 2;
				pay_name = "微信";
			}
			var openid = GetQueryString('openid');
			if (pay_id == 2 && openid == '') {
				alert('no openid');
				return false
			} else {
				console.info(openid);
			}
			for (var i = 0; i < goodsAllSub.length; i++) {
				if ($(goodsAllSub).eq(i).attr('data-is_coupon') == 1) {
					//一件商品
					var oneGoods = {};
					oneGoods.user_id = uid;
					oneGoods.consignee = consignee;
					oneGoods.mobile = phoneNumber;
					oneGoods.goods_id = $(goodsAllSub).eq(i).attr('data-goods_id');
					oneGoods.goods_name = $(goodsAllSub).eq(i).find("h4").eq(0).html();
					oneGoods.goods_number = $(goodsAllSub).eq(i).find(".number").eq(0).html();
					oneGoods.goods_price = $(goodsAllSub).eq(i).find(".teaPrice").eq(0).html();
					oneGoods.address = userAdress;
					oneGoods.pay_id = pay_id;
					oneGoods.pay_name = pay_name;
					oneGoods.seller_id = $(goodsAllSub).eq(i).parents(".shop").find(".shops").attr('data-seller_id');
					oneGoods.coupon_id = $(goodsAllSub).eq(i).parents(".shop").find(".shops").attr('data-coupon_id');
					oneGoods.coupon_no = $(goodsAllSub).eq(i).parents(".shop").find(".shops").attr('data-coupon_no');
					oneGoods.c_money = $(goodsAllSub).eq(i).parents(".shop").find(".shops").attr('data-money');
					oneGoods.order_amount = $(goodsAllSub).eq(i).find(".onePay").eq(0).html();
					oneGoods.sum1 = zongjiage;
					allGoods.push(oneGoods);
				} else {
					var oneGoodsNoc = {};
					oneGoodsNoc.user_id = uid;
					oneGoodsNoc.consignee = consignee;
					oneGoodsNoc.mobile = phoneNumber;
					oneGoodsNoc.goods_id = $(goodsAllSub).eq(i).attr('data-goods_id');
					oneGoodsNoc.goods_name = $(goodsAllSub).eq(i).find("h4").eq(0).html();
					oneGoodsNoc.goods_number = $(goodsAllSub).eq(i).find(".number").eq(0).html();
					oneGoodsNoc.goods_price = $(goodsAllSub).eq(i).find(".teaPrice").eq(0).html();
					oneGoodsNoc.address = userAdress;
					oneGoodsNoc.pay_id = pay_id;
					oneGoodsNoc.pay_name = pay_name;
					oneGoodsNoc.seller_id = $(goodsAllSub).eq(i).parents(".shop").find(".shops").attr('data-seller_id');
					oneGoodsNoc.order_amount = $(goodsAllSub).eq(i).find(".onePay").eq(0).html();
					oneGoodsNoc.sum1 = zongjiage;
					allGoods.push(oneGoodsNoc);
				}
			}
			$.ajax({
				url: 'http://www.teaweilai.com/app/Admin/Order/CreateOrder',
				type: 'POST',
				dataType: 'json',
				data: {
					arr: allGoods,
					point: $(".surePrize").html(),
					random_id: $(".getPrize option:checked").attr('data-random_id')
				},
				beforeSend: function() {
					// console.log(allGoods);
				},
				success: function(data) {
					var obj = JSON.parse(data.sing.biz_content);
					if (pay_id == 1) {
						// 支付宝支付

						$.ajax({
							url: 'http://www.teaweilai.com/app/Admin/Payment/getCode',
							type: 'POST',
							dataType: 'json',
							data: {
								order_id: obj.order_id
							},
							beforeSend: function() {},
							success: function(data) {
								// console.log(data)
								if (data.code == 200) {
									alert('支付成功');
									window.location.href = "myself.html";
								} else {
									$("body").html(data);
								}
							}
						})

					} else if (pay_id == 2) {

						var WXobj = null;

						// 微信支付
						$.ajax({
								url: 'http://www.teaweilai.com/app/Admin/PaymentWx/getCodeWx',
								type: 'POST',
								dataType: 'JSON',
								data: {
									order_id: obj.order_id,
									openid: openid,
								},
								beforeSend: function() {
									console.log(obj.order_id);
									// WXobj={"abc":123};
								}
							})
							.done(function(data) {
								//alert(JSON.stringify(data));
								WXobj = JSON.parse(data);
								//	alert(WXobj.appId);
								console.log("success");

								function onBridgeReady() {

									WeixinJSBridge.invoke(
										'getBrandWCPayRequest', WXobj,
										function(res) {
											//返回原因
											// alert(JSON.stringify(res));
											if (res.err_msg == "get_brand_wcpay_request:ok") {
												window.location.href = "http://www.teaweilai.com/app/App/html/paySuccess.html";
											} // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。 
											else {
												window.location.href = "http://www.teaweilai.com/app/App/html/payFail.html";
											}
										}
									);
								}
								if (typeof WeixinJSBridge == "undefined") {
									if (document.addEventListener) {

										document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
									} else if (document.attachEvent) {
										// alert('2');
										document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
										document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
									}
								} else {
									onBridgeReady();
								}
							})
							.fail(function() {
								console.log("error");
							})
						console.log(WXobj);
						window.sessionStorage.removeItem(fromDetail);
						// window.sessionStorage.removeItem("fromCar");
					}
				}

			})
		})
		// 获取地址
	$.ajax({
		url: 'http://www.teaweilai.com/app/Admin/AppAddress/getAddressList',
		type: 'POST',
		dataType: 'json',
		data: {
			user_id: uid
		},
		success: function(data) {
			var addressStr;
			if (changeAddress == 1) {
				addressStr = '<div class="col-xs-6 userName">收货人 :<span>' + consignee +
					'</span></div><div class="col-xs-6"><span class="phoneNumber">' + phoneNumber +
					'</span></div><div class="col-xs-12">收货地址：<span class="userAdress">' + userAdress +
					'</span></div>';
			} else {
				for (var i = 0; i < data.sing.length; i++) {
					if (data.sing[i].is_default == 1) {
						addressStr = '<div class="col-xs-6 userName">收货人 :<span>' + data.sing[i].consignee +
							'</span></div><div class="col-xs-6"><span class="phoneNumber">' + data.sing[i].mobile +
							'</span></div><div class="col-xs-12"><span class="glyphicon glyphicon-map-marker" ></span>收货地址：<span class="userAdress">' + data.sing[i].address +
							'</span></div>';
						window.sessionStorage.removeItem("changeAddress");
					}
				}
			}
			$(".user").html(addressStr);

			if (consignee == null) {
				consignee = $(".userName span").html();
			}
			if (phoneNumber == null) {
				phoneNumber = $(".phoneNumber").html();
			}
			if (userAdress == null) {
				userAdress = $(".userAdress").html();
			}
		}
	})



	// 点击改变地址
	$(".user").click(function(argument) {
			var hasOrder = 1;
			window.sessionStorage.setItem("hasOrder", hasOrder);
			window.location.href = "myAddress.html";
		})
		// 点击店铺名，到店铺详情
	// $(document).on("click", ".shops", function(e) {
	// 		e.preventDefault();
	// 		console.log($(this))
	// 		var sid = $(this).eq(0).attr('data-seller_id');
	// 		window.sessionStorage.setItem("sid", sid);
	// 		window.location.href = "waterBusinessperson.html";
	// 	})
		// 点击商品
	// $(document).on("click", ".goods", function() {
	// 		var gid = $(this).eq(0).attr('data-goods_id');
	// 		window.sessionStorage.setItem("gid", gid);
	// 		window.location.href = "tea_detail.html";
	// 	})
		//点击可用茶券 显示出可以用的茶券
	$(document).on("click", ".yinteaquan", function() {
		if ($('.yinchaquan').html() != '') {
			$('.shadow').removeClass('hide')
			$('.yinchaquan').removeClass('hide')
		} else {
			$(".mask").css({
				display: 'block'
			});
			setTimeout(function() {
				$(".mask").css({
					display: 'none'
				});
			}, 1500)
		}
	})

	//确定使用的茶券 把茶券添加到页面
	$(document).on("click", ".select_quan", function() {
			var inputtag = $('.yin_quanL');
			var ht = '';
			var quan_money = 0
			var data_quanmoney = '';
			var data_quanid = '';
			var data_quanno = '';
			for (var i = 0; i < inputtag.length; i++) {
				if (inputtag[i].checked == true) {
					ht += $(inputtag).eq(i).attr('data_money') + '元，';
					quan_money += Number($(inputtag).eq(i).attr('data_money'));
					data_quanmoney += $(inputtag).eq(i).attr('data_money') + ',';
					data_quanid += $(inputtag).eq(i).val() + ',';
					data_quanno += $(inputtag).eq(i).attr('data_no') + ',';
				}
			}
			ht = ht.substring(0, ht.length - 1)
			data_quanmoney = data_quanmoney.substring(0, data_quanmoney.length - 1)
			data_quanid = data_quanid.substring(0, data_quanid.length - 1)
			data_quanno = data_quanno.substring(0, data_quanno.length - 1)
			console.log(data_quanmoney);
			$('.yinteaquan').html(ht);
			$('.yinteaquan').attr('data_money', quan_money);
			//yin_coupon_id
			//data_no  data_money  value 就是id

			// 确定之后 改变面额   
			// 茶券兑换额  quan_money
			//  茶券的价格是多少
			//  $(yin_goods).eq(i).parents(".shop").find(".shops")
			var yin_goods = $('.goods')
			for (var i = 0; i < yin_goods.length; i++) {
				if ($(yin_goods).eq(i).attr('data-is_coupon') == 1) { // 1是否可以使用茶券
					var goods_price = Number($(yin_goods).eq(i).find(".teaPrice").html()) * Number($(yin_goods).eq(i).find(".number").html())
					if ((goods_price - quan_money) > 0) {
						$(yin_goods).eq(i).find(".onePay").html(goods_price - quan_money)
						$(yin_goods).eq(i).parents(".shop").find(".shops").attr('data-coupon_id', data_quanid)
						$(yin_goods).eq(i).parents(".shop").find(".shops").attr('data-coupon_no', data_quanno)
						$(yin_goods).eq(i).parents(".shop").find(".shops").attr('data-money', data_quanmoney) //券金额
						quan_money = 0
					} else {
						$(yin_goods).eq(i).find(".onePay").eq(0).html(0);
						$(yin_goods).eq(i).parents(".shop").find(".shops").attr('data-coupon_id', data_quanid)
						$(yin_goods).eq(i).parents(".shop").find(".shops").attr('data-coupon_no', data_quanno)
						$(yin_goods).eq(i).parents(".shop").find(".shops").attr('data-money', data_quanmoney) //券金额
						quan_money = quan_money - goods_price
					}
				}
			}
			actual_payment() //算支付价格
			$('.shadow').addClass('hide')
			$('.yinchaquan').addClass('hide')
		})
		//点击阴影消失
	$(document).on("click", ".shadow", function() {
		$('.shadow').addClass('hide')
		$('.yinchaquan').addClass('hide')
	})

})